package com.yeyks.controller;

import com.yeyks.dal.dao.MessageMapper;
import com.yeyks.dal.dao.OrderInfoMapper;
import com.yeyks.service.OrderService;
import com.yeyks.service.PayService;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yeyks.service.OrderService;
import com.yeyks.service.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;

@RestController
@RequestMapping("/ajax/wxpay")
public class WxPayController {
    private Logger logger = LoggerFactory.getLogger(WxPayController.class);

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private PayService payService;

    @ApiIgnore
    @RequestMapping(value = "/payCallback", method = {RequestMethod.POST, RequestMethod.GET} )
    public String payCallback(
            HttpServletRequest request, HttpServletResponse response
    ) {
        String xmlStr = callback2XmlString(request);

        WxPayOrderNotifyResult notifyResult = null;
        try {
            notifyResult = wxPayService.parseOrderNotifyResult(xmlStr);
        } catch (WxPayException e) {
            logger.error("Parse wxpay notify result failed!", e);
        }

        if (notifyResult == null) {

        }

        String resultCode = notifyResult.getResultCode();
        Boolean paySuccess = (resultCode != null && resultCode.equals("SUCCESS"));
        String orderNo = notifyResult.getOutTradeNo();
        orderService.payCallback(orderNo, paySuccess);
        return payService.wxCreateNotifyResult("SUCCESS", "OK");
    }

    @ApiIgnore
    @RequestMapping(value = "/refundCallback", method = {RequestMethod.POST, RequestMethod.GET} )
    public String refundCallback(
            HttpServletRequest request, HttpServletResponse response
    ) throws Exception {
        String xmlStr = callback2XmlString(request);

        WxPayRefundNotifyResult notifyResult = null;
        try {
            notifyResult = wxPayService.parseRefundNotifyResult(xmlStr);
        } catch (WxPayException e) {
            logger.error("Parse wxpay notify result failed!", e);
        }

        if (notifyResult == null) {

        }

        Boolean refundSuccess = (notifyResult.getReqInfo() != null && notifyResult.getReqInfo().getRefundStatus().equals("SUCCESS"));
        WxPayRefundNotifyResult.ReqInfo reqInfo = notifyResult.getReqInfo();
        String orderNo = reqInfo.getOutTradeNo();
        orderService.refundCallback(orderNo, refundSuccess, reqInfo);
        return payService.wxCreateNotifyResult("SUCCESS", "OK");
    }

    private String callback2XmlString(HttpServletRequest request) {
        StringBuffer xmlStr = new StringBuffer();
        try {
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                xmlStr.append(line);
            }

        } catch (Throwable e) {
            logger.error("Read wxpay notify result failed!", e);
        }

        return new String(xmlStr);
    }
}
